package com.woniuxy.moneyapp.app.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.commons.exception.MyException;
import com.woniuxy.commons.util.BeanCopyUtil;
import com.woniuxy.commons.util.DateUtil;
import com.woniuxy.commons.util.Result;
import com.woniuxy.moneyapp.client.CashRecordClient;
import com.woniuxy.moneyapp.client.param.CashDtoToShow;
import com.woniuxy.moneyapp.client.param.CashRecordForm;
import com.woniuxy.moneyapp.client.param.CashRecordInfo;
import com.woniuxy.moneyapp.common.exception.code.FundExceptionCode;
import com.woniuxy.moneyapp.common.utils.CommonUtil;
import com.woniuxy.moneyapp.infra.dto.MyCashRecord;
import com.woniuxy.moneyapp.infra.model.CashRecord;
import com.woniuxy.moneyapp.service.CashRecordService;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author seven
 * @since 2022-08-01
 */
@RestController
public class CashRecordController implements CashRecordClient {

    @Resource
    private CashRecordService cashRecordService;

    @Resource
    private CashRecordClient crc;

    @Override
    public Result addCashRecord(CashRecordInfo cashRecord) {
        if(cashRecordService.save(BeanCopyUtil.copyObject(cashRecord, CashRecord.class)))
            new Result().setCode(200).setMsg("更新交易流水表成功");
        throw new MyException(FundExceptionCode.DAO_ERROR.getCode(),FundExceptionCode.DAO_ERROR.getMsg());
    }

    @Override
    public Result<Page<CashDtoToShow>> cashRecord(CashRecordForm cashRecordForm) {
        //日期是否为空 end为空的话 默认到现在 start为空 默认 现在时间到半年前
        //start
        if(cashRecordForm.getStartDate()==null){
            //半年前的现在
            cashRecordForm.setStartDate(DateUtil
                    .timeFormatString(
                            (System.currentTimeMillis() - 15811200000l), "yyyy-MM-dd HH:mm:ss"));
        }

        if(cashRecordForm.getEndDate()==null){
            //半年前的现在
            cashRecordForm.setEndDate(DateUtil
                    .timeFormatString(
                            System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
        }

        MyCashRecord toSearch = BeanCopyUtil.copyObject(cashRecordForm, MyCashRecord.class);
        toSearch.setStart(CommonUtil.transStrToLocalDateTime(cashRecordForm.getStartDate()));
        toSearch.setEnd(CommonUtil.transStrToLocalDateTime(cashRecordForm.getEndDate()));
        if(toSearch.getEnd().compareTo(toSearch.getStart())<0) throw new MyException(FundExceptionCode.DATE_ERROR.getCode(),FundExceptionCode.DATE_ERROR.getMsg());
        //返回前端
        return new Result<Page<CashDtoToShow>>().setCode(200).setMsg("流水记录").setData(BeanCopyUtil.copyPage(cashRecordService.getCashRecord(toSearch),CashDtoToShow.class));
    }
}

